package com.gombe.credit.app.ui.activity

import android.annotation.SuppressLint
import android.app.PendingIntent
import android.text.Editable
import android.text.SpannableString
import android.text.Spanned
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.text.style.UnderlineSpan
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.activity.result.IntentSenderRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.lifecycleScope
import com.gombe.credit.app.R
import com.gombe.credit.app.base.app.GombeCreditActivityStackManager
import com.gombe.credit.app.common.CommonActivity
import com.gombe.credit.app.configs.GombeCreditApiPath
import com.gombe.credit.app.configs.GombeCreditApiUrl
import com.gombe.credit.app.configs.GombeCreditApiUrl.addCommonParams
import com.gombe.credit.app.configs.GombeCreditConfigs
import com.gombe.credit.app.databinding.ActGombeCreditUserLoginPageBinding
import com.gombe.credit.app.event.GombeCreditEventPointType
import com.gombe.credit.app.event.room.GombeCreditPointManager
import com.gombe.credit.app.request.IHttpCallback
import com.gombe.credit.app.sdk.analyse.util.GombeCreditGoogleUtil
import com.gombe.credit.app.utils.GombeCreditDateUtil
import com.gombe.credit.app.utils.helper.GombeCreditAnalysisHelper
import com.gombe.credit.app.utils.helper.GombeCreditConfigsHelper
import com.gombe.credit.app.utils.log.GombeCreditLogger
import com.gombe.credit.app.utils.shared.GombeCreditSharedHelper
import com.gombe.credit.app.utils.shared.GombeCreditSharedKey
import com.gombe.credit.app.weight.font.LexendMediumEditText
import com.gombe.credit.lib.adapter.GombeCreditOnSingleClickListener
import com.google.android.gms.auth.api.identity.GetPhoneNumberHintIntentRequest
import com.google.android.gms.auth.api.identity.Identity
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject

/**
 * GombeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/11 16:48
 * @Annotation：登录
 */
class ActGombeCreditUserLogin : CommonActivity() {
    lateinit var binding: ActGombeCreditUserLoginPageBinding

    override fun takeGombeCreditRootView(): View {
        binding = ActGombeCreditUserLoginPageBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initGombeCreditView() {
        setGombeCreditRootParentBackgroundColor(getColor(R.color.white))
        setGombeCreditTitleBarVisibility(View.VISIBLE)
        setGombeCreditBackBtnVisibility(View.GONE)
        setGombeCreditTextTitleVisibility(View.GONE)
        setGombeCreditRightBtnVisibility(View.VISIBLE)
        //关闭所有页面
        GombeCreditActivityStackManager.finishAllActivity(ActGombeCreditUserLogin::class.java)
        checkGombeCreditLoginBtnState()
    }

    override fun initGombeCreditListener() {
        //客服
        rootViewBinding.rootCustomer.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                showCustomerDialog("Login Page")
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.CUSTOMER, "Login Page")
            }
        })
        binding.textMobile.setOnClickListener (object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.USER_LOGIN_SELF_MOBILE)
                requestGombeCreditPhoneNumber()
            }
        })
        binding.editMobile.setInputFocusChangeListener(object : LexendMediumEditText.IInputFocusChangeListener {
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
                checkGombeCreditLoginBtnState(hasFocus)
            }
            override fun onCompleteAction(v: View?, remark: String?) {
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_FORM.LOGIN_MOBILE, remark)
            }
        })
        //电话号码入框监听
        binding.editMobile.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                if (takeGombeCreditLoginMobile().isNotEmpty()) {
                    binding.editMobile.setTextColor(getColor(R.color.black))
                }
                checkGombeCreditLoginBtnState(true)
            }
        })
        binding.editMobile.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                binding.editMobile.clearFocus()
                true
            }
            false
        }

        //隐私政策切换
        binding.loginCheckBox.setOnCheckedChangeListener { _, isChecked ->
            checkGombeCreditLoginBtnState(true)
            when (isChecked) {
                true -> {
                    addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.LOGIN_PRIVACY_AGREE)
                }

                false -> {
                    addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.LOGIN_PRIVACY_DENY)
                }
            }
        }

        //登录
        binding.btnLogin.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                binding.editMobile.clearFocus()
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.LOGIN_NEXT, takeGombeCreditLoginMobile())
                onHideSoftInput(binding.editMobile)
                // TODO: 登录注册点下一步 需上报所有埋点
                GombeCreditPointManager.getInstance().manualReport()

                //登录之前，需要验证手机号是否在 app配置 accList 里存在
                val accItem = checkUserLoginConfigAccount()
                //accList 存在该手机号，直接进入登录成功流程
                if (accItem != null){
                    GombeCreditSharedHelper.addGombeCreditSharedData(GombeCreditSharedKey.GOMBECREDIT_IS_CONFIG_ACCOUNT,true)
                    onUserLoginSuccess(accItem.optString("accUid"),accItem.optString("accTk"))
                    return
                }
                doLoginAction()
            }
        })

        //隐私协议
        binding.textLoginPrivacyPolicy.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                val showTitle = getString(R.string.gombe_credit_privacy_policy_title)
                val linkUrl = GombeCreditConfigs.GOMBECREDIT_PRIVACY_POLICY_SENEGAL_LINK
                ActGombeCreditPrivacyPolicy.start(this@ActGombeCreditUserLogin, showTitle, linkUrl)
            }
        })
    }

    @SuppressLint("SetTextI18n")
    override fun takeGombeCreditData() {
        val showZoneCode = "+${GombeCreditSharedHelper.takeGombeCreditSharedString(GombeCreditSharedKey.GOMBECREDIT_TIMEZONE_CODE)}"
//        val zoneCodeSpannable = SpannableString(showZoneCode)
//        //添加下划线
//        zoneCodeSpannable.setSpan(UnderlineSpan(), 0, showZoneCode.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.textLoginZoneCode.text = showZoneCode

        val showPrivacyPolicy = String.format(getString(R.string.gombe_credit_login_privacy_policy), getString(R.string.gombe_credit_privacy_policy_title))
        val privacyPolicySpannable = SpannableString(showPrivacyPolicy)
        val startIndex = showPrivacyPolicy.indexOf(getString(R.string.gombe_credit_privacy_policy_title))
        privacyPolicySpannable.setSpan(ForegroundColorSpan(getColor(R.color.gombe_credit_ff1d1e20)), startIndex, showPrivacyPolicy.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //添加下划线
        privacyPolicySpannable.setSpan(UnderlineSpan(), startIndex, showPrivacyPolicy.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.textLoginPrivacyPolicy.text = privacyPolicySpannable

        binding.editMobile.visibility = View.VISIBLE
        binding.textMobile.visibility = View.VISIBLE
    }

    /**
     * 设置登录按钮状态
     */
    private fun checkGombeCreditLoginBtnState(hasFocus: Boolean = false) {
        if (hasFocus){
            binding.loginMobileLayout.shapeDrawableBuilder
                .setSolidColor(getColor(R.color.transparent))
                .setStrokeColor(getColor(R.color.gombe_credit_ff1d1e20))
                .setStrokeSize(resources.getDimension(com.gombe.credit.lib.R.dimen.dp_1).toInt())
                .intoBackground()
        } else {
            binding.loginMobileLayout.shapeDrawableBuilder
                .setSolidColor(getColor(R.color.gombe_credit_FFF9F9F7))
                .setStrokeColor(getColor(R.color.gombe_credit_FFF9F9F7))
                .setStrokeSize(resources.getDimension(com.gombe.credit.lib.R.dimen.dp_1).toInt())
                .intoBackground()
        }
        binding.imgPhoneNumberErrorIcon.visibility = View.GONE
        binding.loginErrorLayout.visibility = View.INVISIBLE
        binding.editMobile.setTextColor(getColor(R.color.black))
        if (binding.loginCheckBox.isChecked && takeGombeCreditLoginMobile().isNotEmpty()) {
            binding.btnLogin.isEnabled = true
        } else {
            binding.btnLogin.isEnabled = false
        }
    }

    /**
     * 获取电话号码
     */
    fun takeGombeCreditLoginMobile(): String {
        return binding.editMobile.text.toString().trim()
    }

    fun showGombeCreditUserLoginFailure(data: JSONObject) {
        binding.imgPhoneNumberErrorIcon.visibility = View.VISIBLE
        binding.loginErrorLayout.visibility = View.VISIBLE
        binding.editMobile.setTextColor(getColor(R.color.gombe_credit_fff85858))
        binding.loginMobileLayout.shapeDrawableBuilder
            .setSolidColor(getColor(R.color.transparent))
            .setStrokeColor(getColor(R.color.gombe_credit_fff85858))
            .setStrokeSize(resources.getDimension(com.gombe.credit.lib.R.dimen.dp_1).toInt())
            .intoBackground()
    }

    /**
     * 获取本机手机号码
     */
    private fun requestGombeCreditPhoneNumber(){
        val request: GetPhoneNumberHintIntentRequest = GetPhoneNumberHintIntentRequest.builder().build()
        Identity.getSignInClient(this)
            .getPhoneNumberHintIntent(request)
            .addOnSuccessListener { result: PendingIntent ->
                try {
                    phoneNumberHintIntentResultLauncher.launch(IntentSenderRequest.Builder(result).build())
                } catch (e: Exception) {
                    GombeCreditLogger.e("Launching the PendingIntent failed")
                    showGombeCreditInputMobile()
                }
            }
            .addOnFailureListener {
                GombeCreditLogger.e("Phone Number Hint failed : OnFailureListener")
                showGombeCreditInputMobile()
            }
    }

    private val phoneNumberHintIntentResultLauncher = registerForActivityResult(
        ActivityResultContracts.StartIntentSenderForResult()) { result ->
        try {
            var phoneNumber = Identity.getSignInClient(this).getPhoneNumberFromIntent(result.data)
            GombeCreditLogger.e(">>>>>>>>>>>>>>>>>>>>>>>Phone Number $phoneNumber")
            addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_FORM.USER_LOGIN_SELF_MOBILE,phoneNumber)
            //时区区号
            val zoneCode = "+${GombeCreditSharedHelper.takeGombeCreditSharedString(GombeCreditSharedKey.GOMBECREDIT_TIMEZONE_CODE)}"
            phoneNumber = phoneNumber.replace(zoneCode,"")
            binding.editMobile.setText(phoneNumber)
            binding.editMobile.visibility = View.VISIBLE
            binding.textMobile.visibility = View.GONE
            binding.editMobile.requestFocus()
            binding.editMobile.setSelection(takeGombeCreditLoginMobile().length)
        } catch(e: Exception) {
            GombeCreditLogger.e("Phone Number Hint failed：${e.message}")
            addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.USER_LOGIN_SELF_MOBILE_CANCEL,e.message)
            showGombeCreditInputMobile()
        }
    }

    /**
     * 显示手机号码输入框
     */
    private fun showGombeCreditInputMobile(){
        binding.editMobile.visibility = View.VISIBLE
        binding.textMobile.visibility = View.GONE

        lifecycleScope.launch {
            delay(200)
            binding.editMobile.requestFocus()
            onShowSoftInput(binding.editMobile)
            binding.editMobile.setSelection(takeGombeCreditLoginMobile().length) // 将光标设置到文本末尾
        }
    }

    private fun showGombeCreditMainHomePage() {
        onIntent(ActGombeCreditMain::class.java)
        finish()
    }

    /**
     * 登录成功
     */
    private fun onUserLoginSuccess(uid: String, token: String){
        hideGombeCreditLoading()
        //保存手机号码，个人中心使用
        GombeCreditSharedHelper.addGombeCreditSharedData(GombeCreditSharedKey.GOMBECREDIT_MOBILE, takeGombeCreditLoginMobile())
        //保存用户登录时间
        val loginTime = GombeCreditDateUtil.getFormatTime(System.currentTimeMillis(),"dd/MM/yyyy HH:mm:ss")
        GombeCreditSharedHelper.addGombeCreditSharedData(GombeCreditSharedKey.GOMBECREDIT_LOGIN_TIME,loginTime)
        //保存用户登录状态为已登录
        GombeCreditSharedHelper.addGombeCreditSharedData(GombeCreditSharedKey.GOMBECREDIT_LOGIN,true)
        //保存用户id
        GombeCreditSharedHelper.addGombeCreditSharedData(GombeCreditSharedKey.GOMBECREDIT_USERID,uid)
        //保存用户Token
        GombeCreditSharedHelper.addGombeCreditSharedData(GombeCreditSharedKey.GOMBECREDIT_TOKEN,token)
        //初始化analysis lib 赋值 用户id 和 token
        GombeCreditAnalysisHelper.initAnalysisLibAtLoginSuccess()
        //进入主页
        showGombeCreditMainHomePage()
    }

    /**
     * 获取是否是审核账号信息
     */
    private fun checkUserLoginConfigAccount(): JSONObject?{
        //发送验证码之前，需要验证手机号是否在 app配置 accList 里存在
        val customize = GombeCreditConfigsHelper.takeGombeCreditConfigData()
        var accItem: JSONObject? = null
        if (customize != null){
            val accList = customize.optJSONArray("accList")
            if (accList != null && accList.length() > 0){
                for (i in 0..<accList.length()){
                    val obj = accList.optJSONObject(i)
                    if (takeGombeCreditLoginMobile() == obj.optString("accM")){
                        accItem = obj
                        break
                    }
                }
            }
        }
        return accItem
    }

    /**
     * 登录
     */
    private fun doLoginAction(){
        showGombeCreditLoading()
        val httpUrl = GombeCreditApiUrl.takeRequestUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path", GombeCreditApiPath.GOMBECREDIT_PATH.GOMBECREDIT_API_LOGIN_NO_CODE_PATH)
            put("mobile",takeGombeCreditLoginMobile())//手机号
            put("code","0000")//验证码
            put("channelCode", GombeCreditGoogleUtil.getInstallReferrer())//渠道号
            put("subChannelCode", GombeCreditGoogleUtil.getInstallReferrer())//子渠道号
            put("directLoginFlag","YES")//是否直接登录
            put("notBindWalletFlag","YES")//不自动绑卡
            put("loginParam","")
        }
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                if (obj != null){
                    val userId = obj.optString("userId")
                    val userToken = obj.optString("token")
                    val type = obj.optString("type")

                    //是否是渠道用户
                    val isAdSource = obj.optString("isAdSource")
                    if ("YES" == isAdSource){
                        GombeCreditSharedHelper.addGombeCreditSharedData(GombeCreditSharedKey.GOMBECREDIT_IS_ADSOURCE,true)
                    }
                    onUserLoginSuccess(userId,userToken)
                }
            }
            override fun onRequestError(error: JSONObject) {
                showGombeCreditToast(error.optString("errorMsg"))
                showGombeCreditUserLoginFailure(error)
            }
            override fun onRequestFinish() {
                hideGombeCreditLoading()
            }
        })
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_PAGE.LOGIN_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_PAGE.LOGIN_END)
    }
}